<template>
  <div>
    <div class="app-title">
      <span>档次标准工资配置</span>
    </div>
    <!-- 按钮 -->
    <div class="filter-container">
      <el-row>
        <el-col style="text-align:right;margin-top: 1%;">
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-select v-model="listQuery.salaryId" placeholder="请选择" style="float: left;" @change="getList">
            <el-option
              v-for="item in baseDataList"
              :key="item.id"
              :label="item.salaryName"
              :value="item.id"
            />
          </el-select>
        </el-col>
      </el-row>
    </div>
    <!-- 表格部分 -->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :height="tableHeight"
      :data="list"
      :stripe="true"
      fit
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column type="index" align="center" width="50" label="序号" />

      <el-table-column label="人员类别" align="center">
        <template slot-scope="{row}">
          <span>{{ row.personTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职务" align="center">
        <template slot-scope="{row}">
          <span>{{ row.postName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="档次" align="center">
        <template slot-scope="{row}">
          <span>{{ row.gradeLevelName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.salaryMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="100"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->
    <!-- 新增/编辑页面部分 -->
    <el-dialog  v-dialogDrag  
      :close-on-click-modal="false"
      :title="dialogStatus"
      :visible.sync="dialogFormVisible"
      width="20%"
    >
      <el-form
        ref="dataForm"
        class="dialog-backgroundcolor"
        :rules="dataFormRules"
        :model="formData"
        label-position="top"
        label-width="120px"
        size="small"
      >
        <div class="formDeviation">
          <el-row>
            <el-col>
              <el-form-item
                label="人员类别："
                prop="personTypeId"
                class="item-margin"
              >
                <el-select v-model="formData.personTypeId" placeholder="请选择" :disabled="isEdit" @change="queryPostList">
                  <el-option
                    v-for="item in personTypeList"
                    :key="item.id"
                    :label="item.code+'-'+item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                label="职务："
                prop="postId"
                class="item-margin"
              >
                <el-select v-model="formData.postId" placeholder="请选择" :disabled="isEdit" @change="queryGradeList">
                  <el-option
                    v-for="item in postList"
                    :key="item.id"
                    :label="item.code+'-'+item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                label="档次："
                prop="gradeLevelId"
                class="item-margin"
              >
                <el-select v-model="formData.gradeLevelId" placeholder="请选择" :disabled="isEdit">
                  <el-option
                    v-for="item in gradeLevelList"
                    :key="item.id"
                    :label="item.code+'-'+item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item
                style="margin-top:10px"
                label="金额："
                prop="salaryMoney"
                class="item-margin"
              >
                <el-input
                  v-model="formData.salaryMoney"
                  maxlength="8"
                  @input="handleInput"
                  @change="handleChange"
                /></el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col
            style="text-align: center; margin-top:20px; margin-bottom:8px"
          >
            <el-button
              type="primary"
              :loading="saveLoading"
              @click="handleSave()"
            >
              保存
            </el-button>
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { querySalPostByPersonTypeId, querySalPersonTypeAll, querySalPostGradeLevelAll } from '@/api/salaryConfigManage/personTypePostConfig'
import { querySalPostStandardSalaryAll, saveSalPostStandardSalary, updateSalPostStandardSalary,
  deleteSalPostStandardSalary, queryStandardBasedataInfo, checkRepeat } from '@/api/salaryConfigManage/standardSalary'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
export default {
  name: 'PostChildren',
  components: { tableEmpty },
  filters: {
  },
  data() {
    return {
      tableHeight: null,
      that: this,
      list: null,
      total: 0,
      listLoading: false,
      saveLoading: false,
      deleteLoading: false,
      listQuery: {
        type: 'grade',
        salaryId: ''
      },
      formData: {
        id: '',
        personTypeId: '',
        postId: '',
        gradeLevelId: '',
        type: 'grade',
        salaryId: '',
        salaryMoney: ''
      },
      moneyInputValue: '',
      moneyChangeValue: '',
      dialogFormVisible: false,
      dialogStatus: '',
      isEdit: false,
      dataFormRules: {
        personTypeId: [
          { required: true, message: '请输入人员类别', trigger: 'blur' }
        ],
        postId: [
          { required: true, message: '请输入职务', trigger: 'blur' }
        ],
        gradeLevelId: [
          { required: true, message: '请输入档次', trigger: 'blur' }
        ],
        salaryMoney: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ]
      },
      personTypeList: [],
      postList: [],
      gradeLevelList: [],
      baseDataList: []
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.initBaseData()
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
    },
    getList() {
      this.listLoading = true
      querySalPostStandardSalaryAll(this.listQuery).then((response) => {
        this.list = response.data
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 新增档次标准工资
    handleAdd() {
      this.dialogStatus = '新增标准工资'
      this.formData = {
        id: '',
        personTypeId: '',
        postId: '',
        gradeLevelId: '',
        type: 'grade',
        salaryId: this.listQuery.salaryId,
        salaryMoney: ''
      }
      this.dialogFormVisible = true
      this.isEdit = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleEdit(row) {
      this.formData = Object.assign({}, this.formData, row)
      this.dialogFormVisible = true
      this.isEdit = true
      this.queryPostList('edit')
      this.queryGradeList('edit')
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存
    handleSave() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          const tempData = Object.assign({}, this.formData)
          if (tempData.id === '') { // 新增
            const params = { 'salaryId': this.formData.salaryId,
              'personTypeId': this.formData.personTypeId,
              'postId': this.formData.postId,
              'gradeLevelId': this.formData.gradeLevelId,
              'type': this.formData.type }
            checkRepeat(params).then((response) => {
              if (response.data === 0) {
                saveSalPostStandardSalary(tempData).then((response) => {
                  this.dialogFormVisible = false
                  this.$message({
                    showClose: true,
                    message: '保存成功',
                    type: 'success',
                    duration: 4000
                  })
                  this.saveLoading = false
                  this.handleFilter()
                }).catch(() => {
                  this.saveLoading = false
                })
              } else {
                this.$message({
                  showClose: true,
                  message: '该配置项重复',
                  type: 'warning',
                  duration: 4000
                })
                this.saveLoading = false
              }
            })
          } else { // 修改
            updateSalPostStandardSalary(tempData).then((response) => {
              this.dialogFormVisible = false
              this.$message({
                showClose: true,
                message: '编辑成功',
                type: 'success',
                duration: 4000
              })
              this.saveLoading = false
              this.handleFilter()
            }).catch(() => {
              this.saveLoading = false
            })
          }
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定删除吗?', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSalPostStandardSalary(row.id).then((response) => {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success',
            duration: 4000
          })
          this.handleFilter()
        })
      })
    },
    // 查询职务信息
    queryPostList(type) {
      if (type !== 'edit') {
        this.formData.postId = ''
      }
      const params = { 'personTypeId': this.formData.personTypeId }
      querySalPostByPersonTypeId(params).then((response) => {
        this.postList = Object.assign(response.data)
      })
    },

    // 查询档次信息
    queryGradeList(type) {
      if (type !== 'edit') {
        this.formData.gradeLevelId = ''
      }
      const params = { 'personTypeId': this.formData.personTypeId, 'postId': this.formData.postId, type: 'grade' }
      querySalPostGradeLevelAll(params).then((response) => {
        this.gradeLevelList = Object.assign(response.data)
      })
    },

    // 金额文本框
    handleInput() {
      const regex = /^\d{0,16}\.?\d{0,2}$/
      if (!regex.test(this.formData.salaryMoney)) {
        this.formData.salaryMoney = this.moneyInputValue
          ? this.moneyInputValue
          : '0.00'
      } else {
        this.moneyInputValue = this.formData.salaryMoney
      }
    },

    handleChange() {
      const regex = /^((0|[1-9][0-9]{0,17})|([0]\.\d{1,2}|[1-9][0-9]{0,15}\.\d{1,2}))$/
      if (!regex.test(this.formData.salaryMoney)) {
        this.formData.salaryMoney = this.moneyChangeValue
          ? this.moneyChangeValue
          : '0.00'
      } else {
        this.moneyChangeValue = this.formData.salaryMoney
      }
    },
    initBaseData() {
      querySalPersonTypeAll().then((response) => {
        this.personTypeList = Object.assign(response.data)
      })
      queryStandardBasedataInfo().then((response) => {
        this.baseDataList = Object.assign(response.data)
        this.listQuery.salaryId = this.baseDataList[0].id
        this.getList()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.formDeviation {
  margin-left: 18%;
  .el-form-item__error {
    padding-top: 5%;
  }
}
.redstar.el-form-item__error{
  margin-top: 35px !important;
  left: -96px !important;
}
</style>
